<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />
    <ex_super_table_page v-bind="option" ref="SuperTablePage" @selection-change="e => (selection = e)">
    </ex_super_table_page>

    <appointmentSettings ref="appointmentSettingsRef" />
    <appointmentExamine ref="appointmentExamineRef" />
    <appointmentReportAdjust ref="appointmentReportAdjustRef" />
    <common_print_dialog ref="print_variance_receive" :title="$tt('label_generate_receipt_variance_report')"
      :tableVisiable="false" singlePrint :formDefualt='{
      expectedDate: new Date().getTime(), printNumSum: 1, principal: "艾姆勒海外仓储（深圳）有限责任公司", receivingParty: "诚实关税有限责任公司",
    }' :formModel='[{
      grid: [[{ key: "expectedDate", label: "label_receiving_day", type: "date-picker", },
      { key: "vehicleNo", label: "label_tms_vehicle_license_number", attrs: { maxlength: 15, "show-word-limit": true }, },],
      [{ key: "principal", label: "label_principal_aspect", attrs: { maxlength: 30, "show-word-limit": true }, },
      { key: "receivingParty", label: "label_receive_aspect", attrs: { maxlength: 40, "show-word-limit": true }, },],
      [{ span: 12, col: { key: "contractNo", label: "label_srm_contract_management_contract_no", attrs: { maxlength: 40, "show-word-limit": true }, }, },],
      ]
    },
    ]' :formRules='{
      expectedDate: { required: true,type:"number", message: this.$tt("tip_can_no_empty"), label: "label_receiving_day" },
      vehicleNo: { required: true, message: this.$tt("tip_can_no_empty"), label: "label_tms_vehicle_license_number", },
      principal: { required: true, message: this.$tt("tip_can_no_empty"), label: "label_principal_aspect", },
      receivingParty: { required: true, message: this.$tt("tip_can_no_empty"), label: "label_receive_aspect", },
      contractNo: { required: true, message: this.$tt("tip_can_no_empty"), label: "label_srm_contract_management_contract_no", },
    }' previewUrl="/wms-api/inbound/WmsInboundScheduleRpc/generateReceivingVariance.json" :previewHandler="(data) => {
      const { params, ...other } = data
      return { ...other, ...params }
    }" printUrl="/wms-api/inbound/WmsInboundOverseasInboundOrderRpc/printReceivingVariance.json" :printHandler="(data) => {
      const { clientId, fileType, printNumSum, printerName, params, ...other } = data
      if (params.codeList && _.isString(params.codeList)) {
        params.codeList = params.codeList.split(',')
      } else {
        params.codeList = []
      }
      return {
        receivingVarianceParam: Object.assign({}, other, params),
        printList: [{ clientName: clientId, printerName: printerName, printCount: printNumSum, }],
      }
    }" />

    <taskAssign ref="ReceivingTaskAssign" :title="$tt('label_unload_allocation')"
      @afterSubmit="afterSubmitReceivingTask" multiple :intoTableOption="[
      { key: 'code', label: 'label_inbound_code', 'min-width': 140, 'show-overflow-tooltip': true, },
      { key: 'receivingOrderCode', label: 'label_order_code', 'min-width': 120, 'show-overflow-tooltip': true, },
      {
        type: 'operate', operate: [{
          label: 'title_task_assgin_record', click: (row) => this.$refs.dialogTaskDetailReceiving.show({
            title: `${this.$tt('label_inbound_code')}:${row.code}/${this.$tt('label_order_code')}:${row.code}`,
            urlConfig: {
              url: '/wms-api/inbound/WmsInboundOverseasReceivingRpc/selectPage.json',
              data: { inboundOrderCode: row.code }
            }
          })
        }]
      }
    ]" />

    <detail_task_record ref="dialogTaskDetailReceiving" :tableModel="[
      { key: 'code', label: 'label_task_code' },
      { key: 'receivingUserName', label: 'label_receiving_task_user_name' },
      { key: 'receivingUserCode', label: 'label_receiving_task_user_code' },
      { key: 'receivingStatus', label: 'label_receiving_task_status', formatter: (r, c, v, i) => this.$enumShow(v, 'ReceivingTaskStatusEnum') },
    ]" />

    <!-- 车辆照片 -->
    <uploadCarPhotos ref="uploadCarPhotosRef" />
  </div>
</template>
<script>
import qrcode from 'qrcode'


import superTablePageFunction from "@/mixin/super-table-page-function";
import emitOnFunction from "@/mixin/emit-on-function";

import page_table_model_manage from "@/mixin/page_table_model_manage";
let emitKey = "warehouse_appointment>confirm";

import appointmentSettings from "../component/appointmentSettings";
import appointmentExamine from "../component/appointmentExamine";
import appointmentReportAdjust from '../component/appointment_report_adjust';

import transitNoSelect from "../component/transitNo_select.vue";
import customerSelect from "../component/customer_select.vue";
import vehicleNoSelect from "../component/vehicleNo_select.vue";

import common_print_dialog from '@/component/print/common_print_dialog.vue';

import taskAssign from '@/component/wms/taskAssign.vue';
import detail_task_record from '@/component/dialog/detail_task_record.vue';
// 车辆照片
import uploadCarPhotos from "../component/upload_car_photos.vue";
export default {
  title: "title_warehouse_appointment",
  mixins: [
    superTablePageFunction,
    emitOnFunction(emitKey),
    page_table_model_manage
  ],
  components: {
    appointmentSettings,
    appointmentExamine,
    transitNoSelect,
    customerSelect,
    appointmentReportAdjust,
    common_print_dialog,
    taskAssign,
    detail_task_record,
    vehicleNoSelect,
    uploadCarPhotos
  },
  data() {
    return {
      qrcodeUrl: '',
      selection: [],
      status: "",
      statusRadioGroup: [
        "label_all",
        ...(this.$enumOptions.ScheduleStatusEnum
          ? this.$enumOptions.ScheduleStatusEnum.filter(
            it => !["WAIT_ARRIVE", "FINSHED"].includes(it)
          )
          : [])
      ],
      option: {
        search: {
          model: [
            { label: "label_schedule_code", key: "scheduleCode" },
            { label: "label_inbound_code", key: "code" },

            { label: "label_order_code", key: "receivingOrderCode" },

            { label: "label_waybill_code", key: "transitNo", type: transitNoSelect },
            { label: "label_customer_info", key: "customerName", type: customerSelect },
            { label: "label_car_number", key: "vehicleNo", type: vehicleNoSelect },
            {
              label: "label_schedule_status",
              key: "scheduleStatusEnum",
              type: "select",
              enum: "ScheduleStatusEnum"
            },
            {
              label: "label_schedule_method",
              key: "scheduleTypeEnum",
              type: "select",
              enum: "ScheduleTypeEnum"
            },


            {
              label: "label_expected_arrival_date",
              key: "expectedDate",
              type: "date-picker",
              attrs: { type: "datetimerange" },
              keyExtra: {
                _emitKey: "input",
                0: "expectedBeginDate",
                1: "expectedEndDate"
              }
            }
          ]
        },
        actionExtra: [
          {
            label: "label_appointment_QR_download",
            click: this.qrdownload,
            attrs: { type: "primary" },
          },
          {
            label: "label_generate_receipt_variance_report",
            click: this.clickPrintVarianceReceive
          },
          {
            label: "label_unload_allocation",
            attrs: { type: "primary" },
            click: this.clickReceivingTask
          },
          {
            label: "label_schedule_setting",
            attrs: { type: "primary" },
            click: this.appointmentSettingsFn
          },
          {
            label: "label_setting_log",
            attrs: { type: "primary" },
            click: () => {
              this.$router.push({
                path: "./appointment_settings_list"
              });
            }
          },
          {
            label: "label_schedule_examine",
            attrs: { type: "primary" },
            click: () => {
              if (_.isEmpty(this.selection))
                return this.$message.error(this.$tt("tip_please_select_order"));
              this.appointmentExamineFn(this.selection);
            }
          },
          {
            label: "label_arrival_good_info",
            attrs: { type: "primary" },
            click: () => this.exportPDF()
          },
          { label: "label_export", attrs: { type: "primary" }, click: this.exportExcel }
        ],
        table: {
          url: "/wms-api/inbound/WmsInboundScheduleRpc/selectPage.json",
          // urlDataHandle: this.dataHandle,
          model: this.option_table_model()
        }
      }
    };
  },
  mounted() {
    // 生成二维码
    this.initQR()
  },
  methods: {
    initQR(callback) {
      this.$ajax({
        url: "/wms-api/inbound/WmsInboundScheduleRpc/createUrlPrefix.json",
        method: 'post',
        type: 'json',
        success: (res) => {
          this.qrcodeUrl = `${res.data}mobile/warehouse_appointment?warehouseId=${this.$loginUser.currentWarehouseId}`
          if (callback && this.qrcodeUrl) {
            callback()
          }
        }
      })

    },
    option_table_model() {
      return [
        {
          type: "selection",
          clickToggle: true,
          keyGroup: "label_table_operate"
        },
        {
          key: "scheduleCode",
          label: "label_schedule_code",
          width: 150,
          "show-overflow-tooltip": true
        },
        {
          key: "transitNo",
          label: "label_waybill_code",
          width: 100,
          "show-overflow-tooltip": true
        },
        {
          key: "customerName",
          label: "label_customer_name",
          minWidth: 100,
          "show-overflow-tooltip": true
        },
        {
          key: "scheduleTypeEnum",
          label: "label_schedule_method",
          minWidth: 100,
          "show-overflow-tooltip": true,
          formatter: (r, c, v, i) => this.$enumShow(v, "ScheduleTypeEnum")
        },
        {
          key: "scheduleStatusEnum",
          label: "label_schedule_status",
          minWidth: 100,
          "show-overflow-tooltip": true,
          formatter: (r, c, v, i) => this.$enumShow(v, "ScheduleStatusEnum")
        },
        {
          key: "expectedDatetime",
          label: "label_expected_arrival_date",
          minWidth: 160,
          "show-overflow-tooltip": true,
          formatter: (r, c, v, i) => this.$dateFormat(v)
        },
        {
          key: "expectPackagingQty",
          label: "label_declared_package_number_and_receiving",
          minWidth: 160,
          "show-overflow-tooltip": true,
          formatter: (r, c, v, i) => `${v}(${r.receivingPackagingQty})`
        },
        {
          key: "expectBoxQty",
          label: "label_declared_box_number_and_receiving",
          minWidth: 160,
          "show-overflow-tooltip": true,
          formatter: (r, c, v, i) => `${v}(${r.receivingBoxQty})`
        },
        {
          key: "vehicleNo",
          label: "label_car_number",
          minWidth: 100,
          "show-overflow-tooltip": true
        },
        {
          key: "driverName",
          label: "label_driver_name",
          minWidth: 100,
          "show-overflow-tooltip": true
        },
        {
          key: "driverPhone",
          label: "label_driver_phone",
          minWidth: 120,
          "show-overflow-tooltip": true
        },
        {
          key: "volumn",
          label: "label_declare_goods_sum_volume",
          minWidth: 140,
          "show-overflow-tooltip": true
        },
        {
          key: "weight",
          label: "label_declare_goods_sum_weight",
          minWidth: 140,
          "show-overflow-tooltip": true
        },
        {
          key: "reporter",
          label: "label_declare_user",
          minWidth: 100,
          "show-overflow-tooltip": true
        },
        {
          key: "gmtCreate",
          label: "label_schedule_appointment_time",
          width: 140,
          "show-overflow-tooltip": true,
          formatter: (r, c, v, i) => this.$dateFormat(v)
        },
        {
          key: "receivingOrderCodeList",
          label: "label_associated_inbound_code",
          minWidth: 100,
          "show-overflow-tooltip": true,
          render(h, { row }) {
            return (
              <div>
                {
                  row.receivingOrderCodeList?row.receivingOrderCodeList.toString():''
                }
              </div>
            )
          }
        },

        {
          type: "operate",
          width: 160,
          operate: [
            {
              type: "more",
              items: [
                {
                  label: "label_schedule_examine",
                  disabled: row => row.scheduleStatusEnum != "WAIT_CHECK",
                  click: (row, i) => {
                    this.appointmentExamineFn(row);
                  }
                },
                {
                  label: "label_arrival_good_info",
                  click: (row, i) => {
                    this.exportPDF(row)
                  }
                },
                {
                  label: "label_schedule_adjust",
                  disabled: row => row.scheduleTypeEnum != "SYSTEM" || row.scheduleStatusEnum !== "REJECT",
                  click: (row, i) => {
                    this.$refs.appointmentReportAdjustRef.show(row)
                  }
                },
                {
                  label: "title_appointment_report_detail",
                  click: (row, i) => {
                    this.$router.push({
                      path: "./appointment_report_detail",
                      query: { id: row.id }
                    });
                  }
                },
                {
                  label: "label_print_unload_inventory",
                  click: (row, i) => {
                    this.exportUnloadExcel(row)
                  }
                },
                {
                  label: "label_finish_receive", auth: 'wms_overseas_appointment_finish_receive',
                  disabled: (row) => row.scheduleStatusEnum != 'WAIT_INBOUND',
                  click: (row, i) => {
                    this.finishReceive(row)
                  }
                },
                {
                  label: "label_car_photos",
                  click: (row, i) => {
                    this.$refs.uploadCarPhotosRef.show(row)
                  }
                },
              ]
            }
          ]
        }
      ];
    },
    dataHandle(res) {
      return res;
    },
    exportExcel() {
      const params = this.$refs.SuperTablePage.getSearchFormData();

      const scheduleIds = [];
      this.selection.forEach(item => {
        scheduleIds.push(item.id);
      });
      this.$downloadFile({
        url: "/wms-api/inbound/WmsInboundScheduleRpc/exportExcel.json",
        window: true,
        data: {
          ...params,
          scheduleIds: scheduleIds.toString()
        }
      });
    },
    // 增加打印卸货清点单的功能(POST)
    exportUnloadExcel(row) {
      this.$downloadFile({
        url: "/wms-api/inbound/WmsInboundScheduleRpc/exportUnloadExcel.json",
        window: true,
        data: {
          scheduleId: row.id
        }
      });
    },
    exportPDF(row) {
      const params = this.$refs.SuperTablePage.getSearchFormData();

      const scheduleIds = [];
      if (row) {
        scheduleIds.push(row.id);
      } else {
        this.selection.forEach(item => {
          scheduleIds.push(item.id);
        });
      }

      if (scheduleIds.length <= 0) {
        this.$message.error(this.$tt('tip_please_select_dowith_data'))
        return
      }
      console.log(666, scheduleIds)

      this.$downloadFile({
        url: "/wms-api/inbound/WmsInboundScheduleRpc/exportPdf.json",
        window: true,
        data: {
          ...params,
          scheduleIds: scheduleIds.toString()
        }
      });
    },
    appointmentSettingsFn() {
      this.$refs.appointmentSettingsRef.show({ edit: true });
    },
    appointmentExamineFn(rows) {
      if (!Array.isArray(rows)) {
        rows = [rows]
      }
      this.$refs.appointmentExamineRef.show(rows);
    },
    changeStatus(e) {
      this.status = e;
      this.getSuperTablePage().loadDataForSearch();
    },
    //任务分配
    clickReceivingTask(e) {
      let list = this.selection;
      if (list.length <= 0) {
        this.$message.error(this.$tt('tip_please_select_dowith_data'))
        return
      }
      const data = []
      list.forEach(item => {
        data.push(...item.wmsInboundScheduleDetailList)
      })
      this.$refs['ReceivingTaskAssign'].show(this.$loginUser.currentWarehouseId, data)
    },
    afterSubmitReceivingTask({ select, list }) {
      let taskList = []
      list.map(it => {
        select.map(people => {
          taskList.push({
            inboundOrderId: it.inboundOrderId,
            receivingUserId: people.userId,
            receivingUserCode: people.userCode,
            receivingUserName: people.userName,
          })
        })
      })
      this.$ajax({
        url: "/wms-api/inbound/WmsInboundOverseasInboundOrderRpc/assigningReceivingTask.json",
        method: 'post', type: 'json',
        data: { taskList },
        success: (res) => {
          this.$message.success(this.$tt('tip_submit_success'))
          this.reload()
          this.$refs['ReceivingTaskAssign'].hide()
          this.$emitPage('overseas=>receiving_task', 'reload')
        }
      })
    },
    clickPrintVarianceReceive() {
      let list = JSON.parse(JSON.stringify(this.selection));
      if (list.length <= 0) {
        this.$message.error(this.$tt('tip_please_select_dowith_data'))
        return
      }

      const isSameTime = list.every(item => item.expectedDate === list[0].expectedDate)
      const isSameVehicle = list.every(item => item.vehicleNo === list[0].vehicleNo)
      const isFINSHED = list.every(item => item.scheduleStatusEnum === 'FINSHED')

      if (!isSameTime || !isSameVehicle) {
        this.$message.error(this.$tt('tip_some_car_and_date_can_dowith'))
        return
      }
      if (!isFINSHED) {
        this.$message.error(this.$tt('tip_only_handle_schedule_status_finish_data'))
        return
      }

      let data = {
        scheduleIds: [],
        plateNumber: list[0].vehicleNo,
        receivingTime: list[0].expectedDate
      }
      list.forEach(item => {
        data.scheduleIds.push(item.id)
      })
      this.$refs.print_variance_receive.show([], { default: { params:data }, });
    },
    finishReceive(row) {
      this.$ajax({
        url: "/wms-api/inbound/WmsInboundScheduleRpc/completeReceiving.json",
        method: 'post', type: 'json',
        data: { scheduleCode: row.scheduleCode },
        success: (res) => {
          this.$message.success(this.$tt('tip_submit_success'))
          this.reload()
          this.$emitPage('overseas=>receiving_task', 'reload')
        }
      })
    },
    qrdownload() {
      if (this.qrcodeUrl) {
        qrcode.toDataURL(this.qrcodeUrl, {
          margin: 2,
        }).then(url => {
          const iconUrl = url
          const a = document.createElement('a')
          a.download = '预约二维码'
          a.href = iconUrl
          a.click()
        })
      } else (
        this.initQR(this.qrdownload)
      )


    }
  }
};
</script>
<style></style>
